export interface IDateUtils {
	toTimeText: (timeStamp: number, simple: boolean) => string
	isYestday: (date: Date) => boolean
	isYear: (date: Date) => boolean
	formatDateTime: (date: Date | string) => string
}

const toTimeText = (timeStamp: number, simple: boolean) => {
	const dateTime = new Date(timeStamp)
	const currentTime = Date.parse(new Date().toString()) //当前时间
	const timeDiff = currentTime - Date.parse(dateTime.toString()) //与当前时间误差
	let timeText = ''
	if (timeDiff <= 60000) { //一分钟内
		timeText = '刚刚'
	} else if (timeDiff > 60000 && timeDiff < 3600000) {
		//1小时内
		timeText = Math.floor(timeDiff / 60000) + '分钟前'
	} else if (timeDiff >= 3600000 && timeDiff < 86400000 && !isYestday(dateTime)) {
		//今日
		timeText = formatDateTime(dateTime).substr(11, 5)
	} else if (isYestday(dateTime)) {
		//昨天
		timeText = '昨天' + formatDateTime(dateTime).substr(11, 5)
	} else if (isYear(dateTime)) {
		//今年
		timeText = formatDateTime(dateTime).substr(5, simple ? 5 : 14)
	} else {
		//不属于今年
		timeText = formatDateTime(dateTime)
		if (simple) {
			timeText = timeText.substr(2, 8)
		}
	}
	return timeText
}

const isYestday = (date: Date) => {
	const now = new Date().getTime()
	const yesterday = now - 1000 * 60 * 60 * 24
	return date.getTime() < now && date.getTime() > yesterday
}

const isYear = (date: Date) => {
	return date.getFullYear() === new Date().getFullYear()
}

const formatDateTime = (date: Date | string) => {
	if (date === '' || !date) {
		return ''
	}
	let dateString = ''
	const dateObject = new Date(date)
	const y = dateObject.getFullYear()
	dateString += y + '/'
	let m = dateObject.getMonth() + 1
	dateString += (m < 10 ? ('0' + m) : m) + '/'
	let d = dateObject.getDate()
	dateString += (d < 10 ? ('0' + d) : d) + ' '
	let h = dateObject.getHours()
	dateString += (h < 10 ? ('0' + h) : h) + ':'
	let minute = dateObject.getMinutes()
	dateString += (minute < 10 ? ('0' + minute) : minute) + ':'
	let second = dateObject.getSeconds()
	dateString += second < 10 ? ('0' + second) : second
	return dateString
}

const dateUtils: IDateUtils = {
	toTimeText,
	isYestday,
	isYear,
	formatDateTime,
}

export default dateUtils